﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using XXS.Common.Paginate;

namespace XXS.Common
{
    public enum DetailDataUserfor
    {
        Grid,
        Form,
        Tree,
        CompleteTree
    }

    public static class ExtJsonHelper
    {
        /// <summary>
        ///     使用分页数据进行包装
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object ToExtGrid<T>(this IPaginate<T> source) where T : class, new()
        {
            return
                new
                {
                    success = true,
                    items = source.PageData,
                    total = source.SourceCount,
                    page = source.CurrentPage,
                    limit = source.PageSize
                };
        }

        /// <summary>
        ///     使用转换后的分页数据进行包装
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TR"></typeparam>
        /// <param name="source"></param>
        /// <param name="converter"></param>
        /// <returns></returns>
        public static object ToExtGrid<T, TR>(this IPaginate<T> source, Func<T, TR> converter) where T : class, new()
        {
            return
                new
                {
                    success = true,
                    items = source.PageData.Select(converter),
                    total = source.SourceCount,
                    page = source.CurrentPage,
                    limit = source.PageSize
                };
        }

        /// <summary>
        ///     ExtJS 加载数据集默认使用 items 作为数据集合,在更新数据时回复进行UI更新
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object ToExtGrid(this object source)
        {
            if (source is IEnumerable<object> enumrable)
                return ToExtList(enumrable);
            else
                return new { success = true, items = new[] { source } };
        }

        /// <summary>
        ///     ExtJS 加载数据集默认使用 items 作为数据集合,在更新数据时回复进行UI更新
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object ToExtList(this IEnumerable<object> source)
        {
            return new { success = true, items = source };
        }

        /// <summary>
        ///     ExtJS 默认为表单加载数据必须含有[success,data]属性
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object ToExtData(this object source)
        {
            return new { success = true, data = source };
        }

        /// <summary>
        ///     ExtJS 加载数据集默认使用 children 作为数据集合,在更新数据时回复进行UI更新
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object ToExtTree(this IEnumerable<object> source)
        {
            return new { success = true, children = source };
        }

        /// <summary>
        ///     ExtJS 异常的JSON序列化,UI默认值相应error的异常信息,inner1,inner2主要用于调试使用.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static object ToExtError(this Exception ex)
        {
            var res = new Dictionary<string, object>();

            res.Add("success", false);
            res.Add("msg", ex.Message);

            var innerException = ex.InnerException;
            var deep = 1;
            while (innerException != null && deep < 4)
            {
                deep++;

                res.Add($"inner{deep}_{Guid.NewGuid()}", innerException.Message);

                if (innerException.InnerException != null)
                {
                    innerException = innerException.InnerException;
                }
            }

            return res;
        }

        /// <summary>
        /// 清理Word生成的冗余HTML 
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ToCleanWordHtml(this string html)
        {
            StringCollection sc = new StringCollection();
            // get rid of unnecessary tag spans (comments and title)
            sc.Add(@"<!--(\w|\W)+?-->");
            sc.Add(@"<title>(\w|\W)+?</title>");
            // Get rid of classes and styles
            sc.Add(@"\s?class=\w+");
            sc.Add(@"\s+style='[^']+'");
            // Get rid of unnecessary tags
            //sc.Add(@"<(meta|link|/?o:|/?style|/?div|/?st\d|/?head|/?html|body|/?body|/?span|!\[)[^>]*?>");
            sc.Add(@"<(meta|link|/?o:|/?style|/?font|/?strong|/?st\d|/?head|/?html|body|/?body|/?span|!\[)[^>]*?>");
            // Get rid of empty paragraph tags
            sc.Add(@"(<[^>]+>)+ (</\w+>)+");
            // remove bizarre v: element attached to <img> tag
            sc.Add(@"\s+v:\w+=""[^""]+""");
            // remove extra lines
            sc.Add(@"(\n\r){2,}");
            foreach (string s in sc)
            {
                html = Regex.Replace(html, s, "", RegexOptions.IgnoreCase);
            }
            return html;
        }

        /// <summary>
        ///     返回一个 success 操作的 JSON 对象
        /// </summary>
        /// <returns></returns>
        public static object GetExtSuccessResult()
        {
            return new { success = true };
        }

        public static object ToExtSuccess(this object source)
        {
            return new { success = true };
        }

        public static object ToExtFailure(this object source, string message = null)
        {
            return new { success = false, msg = message };
        }

        public static object GetExtFailureResult(string message = null)
        {
            if (!string.IsNullOrEmpty(message))
                return new { success = false };

            return new { success = false, msg = message };
        }
    }
}